#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->pushButton_Send->setEnabled(false);

    server = new QTcpServer(this);
    socket = new QTcpSocket(this);

    connect(server,&QTcpServer::newConnection,this,&MainWindow::server_New_Connect);

}

MainWindow::~MainWindow()
{
    server->close();
    server->deleteLater();
    delete this->socket;
    delete ui;
}



void MainWindow::on_pushButton_Send_clicked()
{
    qDebug() << "Send :"<<ui->textEdit_Send->toPlainText();

    socket->write(ui->textEdit_Send->toPlainText().toLatin1());
    socket->flush();

}

void MainWindow::on_pushButton_Listen_clicked()
{
    if (ui->pushButton_Listen->text() == tr("侦听")){
        //从输入框获取端口号
        int port = ui->lineEdit_Port->text().toInt();
        //监听指定的端口
        if (!server->listen(QHostAddress::Any,port)){
            qDebug() << "err :" << server->errorString();
            return ;
        }

        ui->pushButton_Listen->setText("取消侦听");
        qDebug() << "Listen successfully";
    } else {
        socket->abort();
        server->close();
        ui->pushButton_Listen->setText("侦听");
        ui->pushButton_Send->setEnabled(false);
    }
}

void MainWindow::server_New_Connect()
{
    //获取客户端连接
    socket = server->nextPendingConnection();
    //连接QTcpSocket的信号槽，以读取新数据
    connect(socket,&QTcpSocket::readyRead,this,&MainWindow::socket_Read_Data);
    connect(socket,&QTcpSocket::disconnected,this,&MainWindow::socket_Disconnected);

    ui->pushButton_Send->setEnabled(true);

    qDebug() << "Client connect";
}

void MainWindow::socket_Read_Data()
{
    QByteArray buffer;
    buffer = socket->readAll();

    if (!buffer.isEmpty()){
        ui->textEdit_Recv->setText("");
        ui->textEdit_Recv->setText(tr(buffer));
    }
}

void MainWindow::socket_Disconnected()
{
    ui->pushButton_Send->setEnabled(false);
    qDebug() << "disconnect";
}
